package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.pojo.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.common.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品管理相关接口")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @ApiOperation("新增菜品")
    public Result addDish(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品：{}", dishDTO);
        dishService.addDish(dishDTO);

        // 清理缓存
        String key = "dish_" + dishDTO.getCategoryId();
        clearCache(key);
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("分页查询菜品")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        log.warn("分页查询菜品：{}", dishPageQueryDTO);
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @DeleteMapping
    @ApiOperation("删除菜品")
    public Result<String> deleteByIds(@RequestParam List<Long> ids) {
        log.warn("删除菜品的ids：{}", ids);
        dishService.deleteByIds(ids);

        //清理缓存

        clearCache("dish_*");


        return Result.success();
    }

    @GetMapping("/{dishId}")
    @ApiOperation("根据菜品id查询菜品")
    public Result<DishVO> getById(@PathVariable Long dishId) {
        log.warn("查询的菜品id：{}", dishId);
        DishVO dishVO = dishService.findDishById(dishId);
        return Result.success(dishVO);
    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result<DishDTO> update(@RequestBody DishDTO dishDTO) {
        log.warn("修改的菜品信息：{}", dishDTO);

        dishService.update(dishDTO);
        clearCache("dish_*");
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> findDishByCategoryId(Long categoryId) {
        List<Dish> list = dishService.findDishByCategoryId(categoryId);
        log.warn("查询的菜品分类id和菜品数据：{},{}", categoryId, list);
        return Result.success(list);
    }


    /**
     * 清理缓存
     */
    private void clearCache(String key) {
        Set keys = redisTemplate.keys(key);

        log.info("清理{}的缓存数据", keys);
        redisTemplate.delete(keys);
    }

}
